package cn.tedu.sims.service.impl;

import cn.tedu.sims.ex.ServiceException;
import cn.tedu.sims.mapper.LocationMapper;
import cn.tedu.sims.mapper.ReportingUserMapper;
import cn.tedu.sims.mapper.UserRoleMapper;
import cn.tedu.sims.pojo.dto.*;
import cn.tedu.sims.pojo.entity.Location;
import cn.tedu.sims.pojo.entity.User;
import cn.tedu.sims.pojo.entity.UserRole;
import cn.tedu.sims.pojo.vo.ReportingUserVO;
import cn.tedu.sims.pojo.vo.UserRoleVO;
import cn.tedu.sims.service.IReportingUserService;
import cn.tedu.sims.util.EmailUtil;
import cn.tedu.sims.web.ServiceCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ReportingUserImpl implements IReportingUserService {
    @Autowired
    ReportingUserMapper reportingUserMapper;

    @Autowired
    UserRoleMapper userRoleMapper;

    @Autowired
    LocationMapper locationMapper;

    @Autowired
    EmailUtil emailUtil;

    @Override
    public List<ReportingUserVO> list() {
        log.debug("开始处理【查询列表】的业务,无参数");
        return reportingUserMapper.list();
    }

    @Override
    public List<ReportingUserVO> listStateId() {
        log.debug("开始处理【查询回收站列表】的业务,无参数");
        return reportingUserMapper.listStateId();
    }

    @Override
    public List<ReportingUserVO> listCheckPending() {
        log.debug("开始处理【查询待审核列表】的业务,无参数");
        return reportingUserMapper.listCheckPending();
    }

    @Override
    public List<ReportingUserVO> selectUserHaHa(ReportingUserHaHaDTO userHaHa) {
        log.debug("开始处理【模糊查询列表】的业务{},参数",userHaHa);
        if (null != userHaHa.getState() && "正常".equals(userHaHa.getState().trim())){
            userHaHa.setState("1");
        }
        if (null != userHaHa.getState() && "冻结".equals(userHaHa.getState().trim())){
            userHaHa.setState("2");
        }
        return reportingUserMapper.selectUserHaHa(userHaHa);
    }

    @Override
    public UserRoleVO selectUserParticulars(Long id) {
        return reportingUserMapper.selectUserParticulars(id);
    }

    @Override
    public User selectById(int id) {
        return reportingUserMapper.selectById(id);
    }

    @Override
    public void updatePassword(UpdatePasswordDTO updatePassword) {
        log.debug("开始处理【修改密码】的业务,参数:{}",updatePassword);
        String password = updatePassword.getPassword();
        if (password!=null){
            BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
            String encodePassword = passwordEncoder.encode(password);
            updatePassword.setPassword(encodePassword);
            int rows = reportingUserMapper.updatePassword(updatePassword);
            if (rows !=1){
                String message = "添加密码失败,服务器忙,请稍后再试! ";
                log.debug(message);
                throw new ServiceException(ServiceCode.ERR_UPDATE, message);
            }
        }
    }

    @Override
    public void updateStateId(Long id) {
        log.debug("开始处理【修改状态】的业务,参数{}",id);
        User user = new User();
        user.setId(id);
        user.setState(3);
        reportingUserMapper.updateStateId(user);
    }

    public void updateStateIda(Long id) {
        log.debug("开始处理【修改状态】的业务,参数{}",id);
        User user = new User();
        user.setId(id);
        user.setState(1);
        reportingUserMapper.updateStateId(user);
    }

    @Override
    public void delete(Long id) {
        log.debug("开始处理[根据id删除用户]的业务,参数: {}", id);
        User user = reportingUserMapper.selectByStateLocationId(id);
        if (user == null){
            // 是: 无此id对应的数据,将不允许执行删除操作,则抛出异常
            String message = "删除用户失败,尝试访问的数据不存在! ";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        if (user.getState() < 3){
            String message = "删除用户失败！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        if (user.getInternalUnitId() != 0){
            String message = "删除用户失败,你没有此权限！";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        log.debug("即将执行删除,参数{}" ,id);
        int rows = reportingUserMapper.deleteById(id);
        if (rows !=2){
            String message = "删除用户失败,服务器忙,请稍后再试! ";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

//    @Autowired
//    private LocationMapper locationMapper;
    @Override
    public void updateInfoById(Long id, UserRoleDTO userRoleDTO) {
        log.debug("开始处理【修改用户详情】的业务，参数ID：{}, 新数据：{}", id, userRoleDTO);
        // 调用Mapper对象的getDetailsById()方法执行查询
        User user = reportingUserMapper.selectByStateLocationId(id);
        Long roleId = userRoleDTO.getRoleId();


//        Map<String,Object> map = new HashMap<>();
//        map.put("name",name);
//        Location location = locationMapper.getLocation(map);

        // 判断查询结果是否为null
        if (user == null) {
            // 是：此id对应的数据不存在，则抛出异常(ERR_NOT_FOUND)
            String message = "修改用户详情失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        User user1 = new User();
        BeanUtils.copyProperties(userRoleDTO, user1);
        user1.setId(id);
        if (roleId==2){
            user1.setInternalUnitId(0L);
        }else {
            user1.setInternalUnitId(1L);
        }
        // 修改数据
        log.debug("即将修改数据：{}", user1);
        user1.setLocationId(Long.parseLong(userRoleDTO.getUserName()));
        int rows = reportingUserMapper.update(user1);
        if (rows != 1) {
            String message = "修改用户详情失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
        log.debug("开始处理【修改用户角色】的业务");
        UserRole location2 = userRoleMapper.location(id);
        log.debug("location2:{}",location2);
        Long userId = location2.getUserId();
        log.debug("userId:{}",userId);
        UserRole userRole = new UserRole();
        log.debug("userRoleDTO:{}",userRoleDTO);
        BeanUtils.copyProperties(userRoleDTO, userRole);
        userRole.setUserId(userId);
        log.debug("即将修改数据：{}", userRole);
        try {
            userRoleMapper.update(userRole);
        }catch (Exception e){
            String message = "修改用户角色失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
//        log.debug("开始处理【修改用户地址】的业务");
//        User location1 = reportingUserMapper.location(id);
//        Long locationId = location1.getLocationId();
//        Location location = new Location();
//        BeanUtils.copyProperties(userRoleDTO, location);
//        location.setId(locationId);
//        log.debug("即将修改数据：{}", location);
//
//        try {
//            locationMapper.update(location);
//        }catch (Exception e){
//            String message = "修改用户地址失败，服务器忙，请稍后再次尝试！" + e.getMessage();
//            log.warn(message);
//            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
//        }
    }

    @Override
    public void updateStatus(UpdateStatusDTO updateStatusDTO) {
        log.debug("开始处理[根据id修改用户状态]的业务,参数: {}", updateStatusDTO);
        if (updateStatusDTO.getState().equals("冻结")){
            updateStatusDTO.setState("1");
        }else if (updateStatusDTO.getState().equals("正常")){
            updateStatusDTO.setState("2");
        }
        log.debug("即将执行修改状态的业务,参数{}" ,updateStatusDTO);
        User user1 = new User();
        Long id = updateStatusDTO.getId();
        BeanUtils.copyProperties(updateStatusDTO, user1);
        user1.setId(id);
        int rows = reportingUserMapper.updateStatus(updateStatusDTO);
        if (rows !=1){
            String message = "修改用户失败,服务器忙,请稍后再试! ";
            log.debug(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
    }

    @Override
    public void userUpdates(Long id) {
        log.debug("开始处理【审核用户】的业务{},参数",id);
        reportingUserMapper.userUpdates(id,1);
    }

    @Override
    public void rejected(ProjectRejectDTO projectRejectDTO) {
        log.debug("开始处理【驳回】的业务,参数:{}",projectRejectDTO);
        String to = projectRejectDTO.getEmail();
        String subject = "体育局体育产业基地";
        String content = projectRejectDTO.getRejectMessage();
        emailUtil.sendMessage(to, subject,content);
        User user = new User();
        Long id = projectRejectDTO.getProjectId();
        user.setId(id);
        user.setState(3);
        reportingUserMapper.updateStateId(user);
    }
}
